const db = uniCloud.database();
const uniID = require('uni-id-common')

exports.main = async (event, context) => {
	const uniIDIns = uniID.createInstance({ context });
	let body = event;
	if (event.body != undefined) {
		body = JSON.parse(event.body)
	}
	console.log(await uniIDIns.checkToken(body.uniIdToken))
	const { uid } = await uniIDIns.checkToken(body.uniIdToken);
	if (!uid) {
	    return { code: 403, msg: "身份验证失败" };
	}
  
  try {
    const res = await db.collection("consultants").where({
      user_id: uid
    }).get();

    if (res.data.length > 0) {
      return {
        code: 0,
        data: {
		  uid,
          avatar: res.data[0].avatar,
          name: res.data[0].name,
		  experience: res.data[0].experience,
		  expertise: res.data[0].expertise,
		  rating:res.data[0].rating || 0
        }
      };
    } else {
      return {
        code: 1,
        message: "未找到咨询师信息",
        data: {
		  uid,
          avatar: "/static/logo.png",
          name: "未填写名称",
		  experience: undefined,
		  expertise: undefined
        }
      };
    }
  } catch (error) {
    console.error("Database query failed:", error);
    return {
      code: -6,
      message: "数据库查询失败",
      data: {
	    uid,
        avatar: "/static/logo.png",
        name: "未填写名称",
		experience: undefined,
		expertise: undefined
      }
    };
  }
};